#!/usr/bin/env python

"""
$Id: headers.py 1580 2010-04-16 19:57:00Z stamparm $

This file is part of the sqlmap project, http://sqlmap.sourceforge.net.

Copyright (c) 2007-2010 Bernardo Damele A. G. <bernardo.damele@gmail.com>
Copyright (c) 2006 Daniele Bellucci <daniele.bellucci@gmail.com>

sqlmap is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation version 2 of the License.

sqlmap is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
details.

You should have received a copy of the GNU General Public License along
with sqlmap; if not, write to the Free Software Foundation, Inc., 51
Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""

import os
import sys
import codecs
from StringIO import StringIO
from xml.sax import parse
from handler import FingerprintHandler

#BannerPath = sys.path[0] + r'\banners/'
BannerPath = os.path.abspath(os.path.dirname(__file__)) + r'/banners/'

def checkFile(filename):
    """
    @param filename: filename to check if it exists.
    @type filename: C{str}
    """

    if not os.path.exists(filename):
        print "unable to read file '%s'" % filename
        sys.exit(0)

def parseXmlFile(xmlFile, handler):
    xfile = codecs.open(xmlFile, 'rb')
    content = xfile.read()
    stream = StringIO(content)
    parse(stream, handler)
    stream.close()
    xfile.close()

def headersParser(headers,headersFp):
    """
    This function calls a class that parses the input HTTP headers to
    fingerprint the back-end database management system operating system
    and the web application technology
    """

    topHeaders = {
                   "cookie":                          os.path.join(BannerPath, "cookie.xml"),
                   "microsoftsharepointteamservices": os.path.join(BannerPath, "sharepoint.xml"),
                   "server":                          os.path.join(BannerPath, "server.xml"),
                   "servlet-engine":                  os.path.join(BannerPath, "servlet.xml"),
                   "set-cookie":                      os.path.join(BannerPath, "cookie.xml"),
                   "x-aspnet-version":                os.path.join(BannerPath, "x-aspnet-version.xml"),
                   "x-powered-by":                    os.path.join(BannerPath, "x-powered-by.xml")
                 }

    for header in headers:
        if header in topHeaders.keys():
            value   = headers[header]
            xmlfile = topHeaders[header]

            checkFile(xmlfile)

            handler = FingerprintHandler(value, headersFp)

            parseXmlFile(xmlfile, handler)
            parseXmlFile(BannerPath+'generic.xml', handler)
